package pl.edu.mimuw.irs.core.global;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import pl.edu.mimuw.irs.core.exception.InternalException;
import pl.edu.mimuw.irs.core.exception.InternalException.Cause;

/**
 * @author Jakub Rauch
 * Created on: 2009-05-07
 */
public class IDManager implements Serializable {
	
	private static final long serialVersionUID = 1190763315242810833L;
	
	// *** Static attributes
	
	private Set<String> usedIds = new HashSet<String>();
	public synchronized String getPrefixedNewId(String prefix) {
		if (!getUsedIds().contains(prefix)) return prefix;
		String newId;
		String[] array = splitId(prefix);
		int counter = Integer.valueOf("0" + array[1]);
		do {
			newId = array[0] + counter++;
		} while (getUsedIds().contains(newId));
		return newId;
	}
	public synchronized String getNewId() {
		return getPrefixedNewId("");
	}
	public synchronized Set<String> getUsedIds() {
		if (usedIds == null) usedIds = new HashSet<String>();
		return usedIds;
	}
	
	// *** Attributes
	
	// *** Methods

	public void changeId(String oldId, String newId) {
		if (oldId != null) {
			getUsedIds().remove(oldId);
		}
		if (newId != null) {
			if (getUsedIds().contains(newId)) throw new InternalException(Cause.GLOBAL_REPEATED_ID);
			getUsedIds().add(newId);
		}
	}
	
	private String[] splitId(String id) {
		String[] splitted = new String[2];
		char[] chars = id.toCharArray();
		int lastInt = chars.length;
		for (int i = 0; i < id.length(); i++) {
			if (Character.isDigit(chars[i])) {
				if (lastInt > i) lastInt = i;
			} else {
				lastInt = chars.length;
			}
		}
		splitted[0] = id.substring(0, lastInt);
		splitted[1] = id.substring(lastInt, id.length());
		return splitted;
	}
	
	public void remove(String id) {
		getUsedIds().remove(id);
	}
}
